﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace SearchInFiles.Lib.Controls
{
    public class TextBoxAttachedProperties
    {
        public static bool GetIsOnlyNumber(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsOnlyNumberProperty);
        }
        public static void SetIsOnlyNumber(DependencyObject obj, bool value)
        {
            obj.SetValue(IsOnlyNumberProperty, value);
        }
        public static readonly DependencyProperty IsOnlyNumberProperty = DependencyProperty.RegisterAttached("IsOnlyNumber", typeof(bool), typeof(TextBox),
            new PropertyMetadata(false, (s, e) =>
                {
                    if (s is TextBox textBox)
                    {
                        textBox.SetValue(InputMethod.IsInputMethodEnabledProperty, !(bool)e.NewValue);
                        textBox.PreviewTextInput -= TxtInput;
                        if ((bool)e.NewValue)
                        {
                            textBox.PreviewTextInput += TxtInput;
                        }
                    }
                }));
        private static void TxtInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            try { e.Handled = !char.IsNumber(e.Text[0]); }
            catch { e.Handled = true; }

        }

    }
}
